package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService userSearchService;



    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //1.构建查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //添加关键词查询
        if (StringUtils.isBlank(dto.getSearchWords())) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            QueryBuilder query = QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR);
            boolQuery.must(query);

            //异步保存用户搜索记录
            ApUser user = AppThreadLocalUtil.getUser();
            if (user != null){
                userSearchService.insert(dto.getSearchWords(),user.getId());
            }
        }
        //添加时间范围查询
        if (dto.getMinBehotTime() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        }
        //添加分页查询
        if (dto.getPageSize() > 0) {
            dto.setPageSize(20);
        }
        searchBuilder.from(dto.getFromIndex()).size(dto.getPageSize());

        //查询高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title").preTags("<font style='color: red; font-size: inherit;'>").postTags("</font>");
        searchBuilder.query(boolQuery);

        searchBuilder.highlighter(highlightBuilder);

        //时间倒序
        searchBuilder.sort("publishTime", SortOrder.DESC);
        searchRequest.source(searchBuilder);
        //2.执行查询
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        //3.解析结果
        ArrayList<Map> list = new ArrayList<>();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map map = JSON.parseObject(sourceAsString, Map.class);

            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() > 0){
                HighlightField highlightField = highlightFields.get("title");
                Text[] fragments = highlightField.getFragments();
                String hTitle = StringUtils.join(fragments);
                map.put("h_title",hTitle);
            }else {
                map.put("h_title",map.get("title"));
            }
            list.add(map);
        }
        return ResponseResult.okResult(list);
    }
}































